package com.jnu.assistant.controller;

import com.jnu.assistant.pojo.Conversation;
import com.jnu.assistant.pojo.Result;
import com.jnu.assistant.pojo.UserSessionId;
import com.jnu.assistant.service.ChatService;
import com.jnu.assistant.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.List;

@Slf4j
@RestController
public class ChatController {

    @Autowired
    private ChatService chatService;

    @PostMapping("/chat/addsession")
    public Result addSession(@RequestHeader("token") String token, @RequestHeader("title") String title)
    {
        try {
            String uncode_title= URLDecoder.decode(title, "UTF-8");
            int userId= (int) JwtUtils.parseJWT(token).get("userId");
            UserSessionId  userSessionId=new UserSessionId();
            userSessionId.setUserId(userId);
            userSessionId.setTitle(uncode_title);
            chatService.addSession(userSessionId);
            log.info("令牌是："+userId);
            log.info("名称是："+uncode_title);
            return Result.success(userSessionId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @GetMapping("/chat/getsession")
    public Result getSession(@RequestHeader("token") String token)
    {
        int userId= (int) JwtUtils.parseJWT(token).get("userId");
        List<UserSessionId> map=chatService.getSession(userId);
        return Result.success(map);
    }

    @DeleteMapping("/chat/deletesession/{sessionId}")
    public Result deleteSession(@PathVariable  int sessionId)
    {
        log.info("会话ID是："+sessionId);
        chatService.deleteConversations(sessionId);
        chatService.deleteSession(sessionId);
        return Result.success();
    }

    @PostMapping("/chat/addconversation")
    public Result addconversation(@RequestBody Conversation conversation){

        chatService.addConversation(conversation);
        log.info(conversation.toString());
        return Result.success();
    }

    @GetMapping("/chat/getconversation/{sessionId}")
    public Result getconversation(@PathVariable int sessionId)
    {
        List<Conversation> conversations=chatService.getConversations(sessionId);
        return Result.success(conversations);
    }

}
